package com.huaxin.hxcloud.work;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.Toast;

import com.huamaitel.api.HMDefines;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;

/**
 * @author songxf
 *         created at 2017/7/11 14:57
 * @desc 华迈视频播放界面
 */

public class HxHuaMaiPlayActivity extends BaseActivity implements GestureDetector.OnGestureListener {

    private static final String  TAG          = "HxHuaMaiPlayActivity";
    private              boolean mIsPlaying   = false; // Is playing video...
    private              boolean mIfLogin     = false; // If login...
    private              boolean mIfExit      = false; // If exit the activity...
    private              boolean mIsListening = false; // Is listening...
    private              boolean mIsRecording = false; // Is Recording...
    private              boolean mIsTalking   = false; // Is talking...


    private int mNodeId       = 0; // The node id.
    private int mChannelIndex = 0; // The channel index.
    private int mVideoStream  = HMDefines.CodeStream.MAIN_STREAM; // The video
    private GestureDetector mDetector;

    // stream
    // (Main/sub
    // video
    // stream.)
    @Override
    protected int getContentViewId() {
        return R.layout.activity_huamai_play;
    }

    @Override
    public void initView() {
        // 让屏幕保持不暗不关闭
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


        Intent intent = getIntent();
        mNodeId = intent.getIntExtra(BaseApp.NODE_ID, 0);
        mChannelIndex = intent.getIntExtra(BaseApp.CHANNEL, 0);
        mVideoStream = intent.getIntExtra(BaseApp.VIDEO_STREAM, HMDefines.CodeStream.MAIN_STREAM);
        Log.d(TAG, "mNodeId: ---" + mNodeId);
        Log.d(TAG, "mChannelIndex: ---" + mChannelIndex);
        Log.d(TAG, "mVideoStream: ---" + mVideoStream);
        openVideo();
        //手势监听
        mDetector = new GestureDetector(this, this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mDetector.onTouchEvent(event);
    }

    @Override
    public void initData() {

    }

    /**
     * @desc 登录 & 打开视频
     * @author songxf
     * created at 2017/7/11 15:20
     */
    private void openVideo() {
        new Thread() {
            @Override
            public void run() {
                super.run();

                if (BaseApp.mIsUserLogin) {
                    // 从互联网登录
                    if (mNodeId == 0) {
                        return;
                    }
                    // Step 1: Login the device.

                    BaseApp.mUserId = BaseApp.getJni().loginEx(mNodeId, HMDefines.ConnectMode.CONN_MODE_DEFAULT);
                    if (BaseApp.mUserId == 0) {
                        return;
                    }
                } else {
                    /**
                     * 从局域网登录 TODO:异常处理 从局域网登录（本地设备） 调试时需要注意手机的网络为同一个局域网 如果设备进行了设置，输入相应的账号密码。默认账号为：guest,密码不填。 此处请检查输入的正确性，代码中没有做相关信息正确性检查。
                     */
                    String sIp = getIntent().getStringExtra("ip");
                    String sPort = getIntent().getStringExtra("port");
                    String sUser = getIntent().getStringExtra("user");
                    String sPass = getIntent().getStringExtra("pass");
                    String sSn = getIntent().getStringExtra("sn");
                    if (sIp != null && sPort != null && sSn != null && sUser != null) {
                        // Step 1: Login the device.
                        BaseApp.mUserId = BaseApp.getJni().login(sIp, Short.parseShort(sPort), sSn, sUser, sPass);
                        if (BaseApp.mUserId == 0) {
                            return;
                        }
                    }
                }

                mIfLogin = true;

                /**
                 * Step 2: Get device information. TODO:异常处理 当设备不在线，执行这一步容易返回为空。测试时请检查一下设备是否在线！！ 可参考SDK文档 添加 Online这个接口进行判断。
                 */
                BaseApp.mDeviceInfo = BaseApp.getJni().getDeviceInfo(BaseApp.mUserId);
                BaseApp.mChannelCapacity = BaseApp.getJni().getChannelCapacity(BaseApp.mUserId);
                if (BaseApp.mDeviceInfo == null) {
                    return;
                }
                // Step 3: Start video
                HMDefines.OpenVideoParam param = new HMDefines.OpenVideoParam();
                param.channel = mChannelIndex;
                param.codeStream = HMDefines.CodeStream.MAIN_STREAM;
                param.videoType = HMDefines.VideoStream.REAL_STREAM;
                HMDefines.OpenVideoRes res = new HMDefines.OpenVideoRes();
                Log.d(TAG, "run: ---->" + BaseApp.mUserId);
                BaseApp.mVideoHandle = BaseApp.getJni().startVideo(BaseApp.mUserId, param, res);

                if (BaseApp.mVideoHandle == -1) {
                    mIsPlaying = false;
                    return;
                }
                /**
                 * TODO：异常处理 startVideo成功后 ，执行 setNetworkCallback 回调函数检测网络数据。 为保证设备信息获取到，可以再执行一次getDeviceInfo操作。 如添加了进度条，在此时进行释放。
                 *
                 */
                mIsPlaying = true;
            }
        }.start();
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setTitle("确定要退出视频播放吗？").setIcon(android.R.drawable.ic_dialog_info).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Exit the play activity for exiting.
                if (!mIfExit) {
                    exitPlayActivity();
                }
                HxHuaMaiPlayActivity.this.finish();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // do nothing……
            }
        }).show();
    }

    private void exitPlayActivity() {
        // Avoid calling this function many times.
        mIfExit = true;

        // Close some resources.
        new Thread() {
            public void run() {
                releaseResources();
            }

        }.start();

        // Back to the device list activity.
        backtoDeviceList();
    }

    private void backtoDeviceList() {
        this.finish();
    }

    private void releaseResources() {
        if (mIsPlaying) {
            int result = BaseApp.getJni().stopVideo(BaseApp.mVideoHandle);
            if (result != 0) {
                Log.e(TAG, "stopvideo fail.");
            } else {
                Log.i(TAG, "stopvideo success.");
            }
            mIsPlaying = false;
        }

        if (mIsRecording) {
            int result = BaseApp.getJni().stopLocalRecord(BaseApp.mRecordHandle);
            if (result != 0) {
                Log.e(TAG, "stopLocalRecord fail.");
            } else {
                Log.i(TAG, "stopLocalRecord success.");
            }
            mIsRecording = false;
        }

        if (mIsTalking) {

            int result = BaseApp.getJni().stopTalk(BaseApp.mTalkHandle);
            if (result != 0) {
                Log.e(TAG, "stopTalk fail.");
            } else {
                Log.i(TAG, "stopTalk success.");
            }
            mIsTalking = false;
        }
        if (mIsListening) {
            int result = BaseApp.getJni().stopAudio(BaseApp.mAudioHandle);
            if (result != 0) {
                Log.e(TAG, "stopAudio fail.");
            } else {
                Log.i(TAG, "stopAudio success.");
            }

            mIsListening = false;
        }

        if (mIfLogin) {
            int result = BaseApp.getJni().logout(BaseApp.mUserId);
            if (result != 0) {
                Log.e(TAG, "logout fail.");
            } else {
                Log.i(TAG, "logout success.");
            }
            mIfExit = false;
        }

    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    //滑屏检测
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {
        float minMove = 120;         //最小滑动距离
        float minVelocity = 0;      //最小滑动速度
        float beginX = e1.getX();
        float endX = e2.getX();
        float beginY = e1.getY();
        float endY = e2.getY();

        //设置摄像头移动
        //userId login 或 hloginEx 之返回句柄。
        //channel 设备通道号
        //ptzCmd 云台相关控制命令。
        //speed  相关操作的速度，其范围为 0-10
        //int i = MainApp.getJni().ptzControl(MainApp.mUserId, mChannelIndex, HMDefines.PtzCommand.PTZACT_RIGHT, 10);
        if (BaseApp.mChannelCapacity[0].ptzSupport == 1) {//云台设备=1
            if (beginX - endX > minMove && Math.abs(velocityX) > minVelocity) {   //左滑
                BaseApp.getJni().ptzControl(BaseApp.mUserId, mChannelIndex, HMDefines.PtzCommand.PTZACT_LEFT, 5);
                // Toast.makeText(this,velocityX+"左滑",Toast.LENGTH_SHORT).show();
                Log.d("----------", "左滑" + ",-->" + velocityX);
            } else if (endX - beginX > minMove && Math.abs(velocityX) > minVelocity) {   //右滑
                BaseApp.getJni().ptzControl(BaseApp.mUserId, mChannelIndex, HMDefines.PtzCommand.PTZACT_RIGHT, 5);
                Log.d("----------", "右滑" + ",-->" + velocityX);
                // Toast.makeText(this,velocityX+"右滑",Toast.LENGTH_SHORT).show();
            } else if (beginY - endY > minMove && Math.abs(velocityY) > minVelocity) {   //上滑
                BaseApp.getJni().ptzControl(BaseApp.mUserId, mChannelIndex, HMDefines.PtzCommand.PTZACT_UP, 5);
                Log.d("----------", "上滑" + ",-->" + velocityX);
                // Toast.makeText(this,velocityX+"上滑",Toast.LENGTH_SHORT).show();
            } else if (endY - beginY > minMove && Math.abs(velocityY) > minVelocity) {   //下滑
                BaseApp.getJni().ptzControl(BaseApp.mUserId, mChannelIndex, HMDefines.PtzCommand.PTZACT_DOWN, 5);
                Log.d("----------", "下滑" + ",-->" + velocityX);
                //Toast.makeText(this,velocityX+"下滑",Toast.LENGTH_SHORT).show();
            }
        } else {
            ToastUtil.showToast("不是云台设备");
        }
        return false;
    }
}
